package com.sftz.modules.minapp.pay.service;

import java.util.Date;
import java.util.List;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.sftz.assets.entities.CourseEntity;
import com.sftz.assets.entities.InstitutionCoursesEntity;
import com.sftz.assets.entities.InstitutionEntity;
import com.sftz.assets.entities.OrderPayRecordEntity;
import com.sftz.assets.entities.SeriesCoursesEntity;
import com.sftz.assets.entities.StudentMajorEntity;
import com.sftz.assets.entities.TOrderEntity;
import com.sftz.assets.entities.UserCoursesltEntity;
import com.sftz.assets.entities.UserProductEntity;
import com.sftz.assets.entities.UserScoreRelationshipEntity;
import com.sftz.assets.enums.CourseStateEnum;
import com.sftz.assets.enums.CourseTypeEnum;
import com.sftz.assets.enums.OrderStatusEnum;
import com.sftz.assets.enums.OrderTypeEnum;
import com.sftz.assets.enums.YesOrNoEnum;
import com.sftz.modules.minapp.pay.dto.OrderDto;
import com.sftz.modules.minapp.pay.form.OrderPayRecordForm;
import com.sftz.modules.minapp.seriesCouresDetail.service.SerirsecoursedetailViewService;
import com.uxuexi.core.common.util.BeanUtil;
import com.uxuexi.core.common.util.DateTimeUtil;
import com.uxuexi.core.common.util.DateUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;

@IocBean
public class WxMpPayOrderService {

	private static final Log log = Logs.get();

	@Inject
	private IDbDao dbDao;

	@Inject
	private SqlManager sqlManager;

	@Inject
	private SerirsecoursedetailViewService serirsecoursedetailViewService;

	@Aop("txDb")
	public boolean charge(OrderDto order) {
		int i = 0;
		boolean flag = false;

		while (!flag) {
			if (i == 10) {
				break;
			}
			i++;
			try {
				flag = charge4Order(order);
			} catch (Exception e) {
				flag = false;
				e.printStackTrace();
			}
		}

		log.info("为用户充值，订单号:" + order.getOrderNo() + ",当前尝试次数:" + i + ",结果:" + flag);
		return flag;
	}

	@Aop("txDb")
	private boolean charge4Order(OrderDto order) {
		Integer orderId = order.getId();
		//1订单改为已完成
		dbDao.update(TOrderEntity.class, Chain.make("orderState", OrderStatusEnum.COMPLETE.intKey()),
				Cnd.where("id", "=", orderId));

		//2用户商品表添加数据
		UserProductEntity up = new UserProductEntity();
		up.setOrderId(orderId);
		up.setProductId(order.getProductId());
		up.setOrderType(order.getOrderType());
		up.setUserId(order.getUserId());
		dbDao.insert(up);

		//当前时间
		Date nowDate = DateTimeUtil.nowDate();
		Integer userId = order.getUserId();
		Integer productId = order.getProductId();
		Integer courseTyp = order.getOrderType();

		UserProductEntity userProductEntity = new UserProductEntity();
		userProductEntity.setPurchaseDate(nowDate);
		userProductEntity.setUserId(userId);
		userProductEntity.setProductId(productId);
		userProductEntity.setOrderType(courseTyp);

		String createTime = DateUtil.Date2String(nowDate);

		//选课表及学生表数据添加

		StudentMajorEntity stu = new StudentMajorEntity();
		UserCoursesltEntity userCourse = new UserCoursesltEntity();
		//购买的是系列课程
		if (courseTyp == OrderTypeEnum.COURSESERIES.intKey()) {
			//添加到选课信息表里--haozhenbin
			UserCoursesltEntity userCour = dbDao.fetch(UserCoursesltEntity.class,
					Cnd.where("userId", "=", userId).and("seriesId", "=", userProductEntity.getProductId()));
			if (Util.isEmpty(userCour) && !Util.isEmpty(userProductEntity)) {
				userCourse.setUserId(userProductEntity.getUserId());
				userCourse.setSeriesId(userProductEntity.getProductId());
				userCourse.setCheckStatus(YesOrNoEnum.NO.intKey());
				dbDao.insert(userCourse);
			}
			//添加进学生表里 
			//查询当前专业属于哪个机构
			SeriesCoursesEntity fetch = dbDao.fetch(SeriesCoursesEntity.class, Cnd.where("id", "=", productId));
			if (!Util.isEmpty(fetch)) {
				Integer insititutionId = fetch.getInsititutionId();
				//---查询该用户是否在学生表中存在并且购买过该专业
				Sql queryStudent = Sqls.create(sqlManager.get("minapp_seriesCourseDetail_student_is_or_no"));
				queryStudent.setParam("majorId", productId);
				queryStudent.setParam("userId", userId);
				queryStudent.setParam("institutionId", insititutionId);
				List<StudentMajorEntity> serCour = DbSqlUtil.query(dbDao, StudentMajorEntity.class, queryStudent);
				//没有购买过
				if (Util.isEmpty(serCour)) {
					stu.setMajorId(productId);
					stu.setUserId(userId);
					stu.setInstitutionId(insititutionId);
					stu.setCreateTime(createTime);
					stu = dbDao.insert(stu);
				}
			}
			//添加报名人数
			String orderNo = order.getOrderNo();
			//添加学习系列课程报名人数
			TOrderEntity tOrderEntity = dbDao.fetch(TOrderEntity.class, Cnd.where("id", "=", order.getId()));
			if (!Util.isEmpty(tOrderEntity)) {
				//如果订单类型为专业，则添加报名人数
				Sql sql = Sqls.create(sqlManager.get("minapp_pay_seriesCourse_addNum"));
				sql.setParam("id", tOrderEntity.getProductId());
				dbDao.execute(sql);

				//查询机构报名人数为null则置为0
				InstitutionEntity ins = dbDao.fetch(InstitutionEntity.class,
						Cnd.where("id", "=", tOrderEntity.getCollegeId()));
				if (Util.isEmpty(ins.getSignCount())) {
					dbDao.update(InstitutionEntity.class, Chain.make("signCount", 0), Cnd.where("id", "=", ins.getId()));
				}
				//修改学院报名人数
				Sql sqlins = Sqls.create(sqlManager.get("minapp_pay_institution_addNum"));
				sqlins.setParam("id", tOrderEntity.getCollegeId());
				dbDao.execute(sqlins);

				log.info("收到付费完成通知,订单号:" + orderNo);
			}
		}
		//购买的是单个课程
		else if (courseTyp == OrderTypeEnum.COURSE.intKey()) {
			//查询当前课程属于个人课程还是机构课程
			CourseEntity course = dbDao.fetch(CourseEntity.class, Cnd.where("id", "=", productId));
			// 添加学习人数
			serirsecoursedetailViewService.addCourseStudyCountNum(productId);
			//机构课程
			if (course.getCourseType() == CourseTypeEnum.INSTITUTIONCOURSE.intKey()) {
				//查询当前课程属于哪个机构
				InstitutionCoursesEntity insCourse = dbDao.fetch(InstitutionCoursesEntity.class,
						Cnd.where("courseId", "=", productId));
				//查询当前课程是否被该用户曾经购买过
				Sql stuCourSql = Sqls.create(sqlManager.get("minapp_seriesCourDetail_buy_ins_single_course"));
				stuCourSql.setParam("courseId", productId);
				stuCourSql.setParam("institutionId", insCourse.getInstitutionId());
				stuCourSql.setParam("userId", userId);
				List<StudentMajorEntity> serCour = DbSqlUtil.query(dbDao, StudentMajorEntity.class, stuCourSql);
					//--------当前课程不属于系列课程,是机构的单个课程
					if (Util.isEmpty(serCour)) {
						//添加学生表
						stu.setInstitutionId(insCourse.getInstitutionId());
						stu.setUserId(userId);
						stu.setCreateTime(createTime);
						stu = dbDao.insert(stu);
						//将课程添加进学生表
						UserScoreRelationshipEntity userScore = new UserScoreRelationshipEntity();
						userScore.setStudentId(stu.getId());
						userScore.setCourseId(productId);
						userScore = dbDao.insert(userScore);
					}
			} else {
				//个人课程
				//查询当前用户是否在学生表存在
				Sql queryS = Sqls.create(sqlManager.get("minapp_seriesCourDetail_query_user_stu_course"));
				queryS.setCondition(Cnd.where("ur.courseId", "=", productId).and("sm.userId", "=", userId));
				StudentMajorEntity fetchEntity = DbSqlUtil.fetchEntity(dbDao, StudentMajorEntity.class, queryS);
				//未购买过
				if (Util.isEmpty(fetchEntity)) {
					stu.setUserId(userId);
					stu.setCreateTime(createTime);
					stu = dbDao.insert(stu);

					UserScoreRelationshipEntity userScore = new UserScoreRelationshipEntity();
					userScore.setStudentId(stu.getId());
					userScore.setCourseId(productId);
					userScore = dbDao.insert(userScore);
				}

			}
		} else {
			log.info("未知的订单类型:" + order.getOrderType() + ",订单号：" + order.getOrderNo());
		}

		return true;
	}

	public OrderDto fetchOrder(String orderNo) {
		Sql sql = Sqls.create(sqlManager.get("minapp_pay_fetch_order"));
		sql.params().set("orderNo", orderNo);

		OrderDto o = DbSqlUtil.fetchEntity(dbDao, OrderDto.class, sql);
		return o;
	}

	@Aop("txDb")
	public boolean addPayRecord(OrderPayRecordForm form) {
		OrderPayRecordEntity en = new OrderPayRecordEntity();
		BeanUtil.copyProperties(form, en);
		dbDao.insert(en);
		return true;
	}
}
